package com.bsj.power.common.config.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsj.power.common.annotation.Log;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.TokenUser;
import com.bsj.power.common.constant.SysLogTitleConst;
import com.bsj.power.common.def.entity.log.SysRecordLog;
import com.bsj.power.common.def.entity.user.User;
import com.bsj.power.common.file.log.OperateLogSaveQueue;
import com.bsj.power.common.mapper.UserMapper;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.common.util.IpUtils;
import com.bsj.power.common.util.ServletUtils;
import com.bsj.power.common.util.StpLoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * @author yinhao
 * @version 1.0
 * @description 日志记录
 * @date 2024/6/3
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    public static final String LOG_ID = "20249527";

    @Autowired
    private UserMapper userMapper;

    /**
     * 处理完请求后执行
     *
     * @param joinPoint
     * @param controllerLog
     * @param jsonResult
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param controllerLog
     * @param e
     */
    @AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    /**
     * 编辑成保存的实体对象
     *
     * @param joinPoint
     * @param controllerLog
     * @param e
     * @param jsonResult
     */
    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            SysRecordLog sysRecordLog = new SysRecordLog();
            sysRecordLog.setStatus(0);
            sysRecordLog.setId(LOG_ID);
            sysRecordLog.setRecordTime(System.currentTimeMillis());
            //请求的IP
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            sysRecordLog.setRecordIp(ip);
            sysRecordLog.setRecordUrl(ServletUtils.getRequest().getRequestURI());

            //设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysRecordLog.setMethod(className + "." + methodName + "()");
            TokenUser tokenInfo = null;
            if ("doLogout".equalsIgnoreCase(methodName)) {
                User user = userMapper.selectById((Integer)joinPoint.getArgs()[0]);
                tokenInfo = new TokenUser();
                BeanUtils.copyProperties(user, tokenInfo);
            }
            if (tokenInfo == null) {
                tokenInfo = StpLoginUserUtil.getTokenUser();
            }

            if (tokenInfo == null) {
                tokenInfo = StpLoginUserUtil.getTokenUserBySaToken(getSessionId(joinPoint.getArgs()));
            }
            sysRecordLog.setRecordId(tokenInfo.getUserId());
            sysRecordLog.setRecordType(tokenInfo.getUserType());
            sysRecordLog.setRecordName(tokenInfo.getUserName());
            if (e != null) {
                sysRecordLog.setStatus(1);
                if (e instanceof ApiException) {
                    ApiException apiException = (ApiException) e;
                    sysRecordLog.setErrorMsg(apiException.getStatus().getMsg());
                } else {
                    sysRecordLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
                }
            }

            //设置请求方式
            sysRecordLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            //处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, sysRecordLog, jsonResult);
            //存储
            log.info("日志保存内容: {}", JSON.toJSONString(sysRecordLog));
            OperateLogSaveQueue.push(JSON.toJSONBytes(sysRecordLog));
        } catch (Exception ex) {
            log.error("操作记录异常信息: {}", ExceptionUtil.getStackStr(ex));
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log          日志
     * @param sysRecordLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysRecordLog sysRecordLog, Object jsonResult) throws Exception {
        // 设置action动作
        sysRecordLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        String title = log.title();
        sysRecordLog.setTitle(log.title());
        // 设置描述

        if (SysLogTitleConst.VIDEO_VIEWING.equals(title) || SysLogTitleConst.PLAY_BACK_DOWNLOAD.equals(title)
                || SysLogTitleConst.PTZ_CONTROL.equals(title)) {
            sysRecordLog.setDesc(log.desc() + joinPoint.getArgs()[0]);
        } else {
            sysRecordLog.setDesc(log.desc());
        }
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, sysRecordLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param sysRecordLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysRecordLog sysRecordLog) throws Exception {
        String requestMethod = sysRecordLog.getRequestMethod();
        if (HttpMethod.GET.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysRecordLog.setRecordParam(StringUtils.substring(params, 0, 2000));
        }
    }

    /**
     * 获取sessionId值
     *
     * @param paramsArray
     * @return java.lang.String
     * @author ljx
     * @time 2024/3/8 10:25
     */
    private String getSessionId(Object[] paramsArray) {
        String sessionId = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (isNotNull(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        sessionId += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return JSONObject.parseObject(sessionId).get("sessionId").toString();
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (isNotNull(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse || o instanceof BindingResult;
    }

    public static boolean isNotNull(Object object) {
        boolean f = object == null;
        return !f;
    }
}
